package test.plural;

public class Complex {
    //（4）编写一个复数类，具有实部、虚部成员变量，可以完成加、减、乘、获得实部和虚部等操作，并编写一个主类对其进行测试。
    public double realPart;//复数实部
    public double imaginaryPart;//复数虚部

    public Complex()//复数类的无参构造方法
    {
        this.imaginaryPart = 0;
        this.realPart = 0;
    }

    public Complex(double realPart, double imaginaryPart)//复数类的有参构造方法
    {
        this.imaginaryPart = imaginaryPart;
        this.realPart = realPart;
    }

    //复数实部和虚部的getter和setter方法
    public double getRealPart() {
        return realPart;
    }

    public void setRealPart(double realPart) {
        this.realPart = realPart;
    }

    public double getImaginaryPart() {
        return imaginaryPart;
    }

    public void setImaginaryPart(double imaginaryPart) {
        this.imaginaryPart = imaginaryPart;
    }

    //复数加法(a+bi)+(c+di)=(a+c)+(b+d)i
    public Complex add(Complex a, Complex b) {
        return new Complex(a.realPart + b.realPart, a.imaginaryPart + b.imaginaryPart);
    }

    //复数减法(a+bi)-(c+di)=(a-c)+(b-d)i
    public Complex subduction(Complex a, Complex b) {
        return new Complex(a.realPart - b.realPart, a.imaginaryPart - b.imaginaryPart);
    }

    //复数乘法(a+bi)*(c+di)=(ac-bd)+(ad+bc)i
    public Complex multiplication(Complex a, Complex b) {
        return new Complex((a.realPart * b.realPart - a.imaginaryPart * b.imaginaryPart), (a.realPart * b.imaginaryPart + a.imaginaryPart * b.realPart));
    }

    //复数除法(a+bi)/(c+di)=(ac+bd)/(c²+d²)+((bc-ad)/(c²+d²))i
    public Complex dividion(Complex a, Complex b) {
        if (b.realPart == 0 && b.imaginaryPart == 0)//排除除数不能为零的情况
        {
            System.out.println("除数不能为零");
        }
        return new Complex(((a.realPart * b.realPart + a.imaginaryPart * b.imaginaryPart) / (b.realPart * b.realPart + b.imaginaryPart * b.imaginaryPart)), ((a.imaginaryPart * b.realPart - a.realPart * b.imaginaryPart) / (b.realPart * b.realPart + b.imaginaryPart * b.imaginaryPart)));
    }

    //复数的模
    public static double module(Complex a) {
        double x = a.realPart * a.realPart + a.imaginaryPart * a.imaginaryPart;
        return Math.sqrt(x);
    }

    //打印输出
    public void print() {
        if (this.imaginaryPart < 0)//当复数的虚部为负数时，避免多打印出一个"+"
        {
            System.out.println(this.realPart + "" + this.imaginaryPart + "i");
        } else {
            System.out.println(this.realPart + "+" + this.imaginaryPart + "i");
        }
    }

}
